﻿using Devonline.AspNetCore;
using Devonline.Core;
using Microsoft.Extensions.Logging;

namespace Devonline.AuxiliaryTools.FileTools;

/// <summary>
/// json 文件操作相关的服务
/// </summary>
public class JsonFileService : DataFileService, IDataFileService, IFileService
{
    /// <summary>
    /// 构造方法
    /// </summary>
    /// <param name="logger">日志</param>
    /// <param name="httpSetting">Http配置项</param>
    public JsonFileService(ILogger<JsonFileService> logger, HttpSetting httpSetting) : base(logger, httpSetting) => _fileExtension = AppSettings.DEFAULT_CONFIG_FILE_EXTENSION;

    /// <summary>
    /// 转换对象为字符串形式
    /// </summary>
    /// <typeparam name="TEntitySet">对象类型</typeparam>
    /// <param name="entitySet">对象值</param>
    /// <param name="index">当前行数</param>
    /// <param name="total">总行数</param>
    /// <returns>转换后的字符串格式</returns>
    protected override string? ConvertTo<TEntitySet>(TEntitySet entitySet, long index, long total)
    {
        var value = entitySet.ToJsonString();
        if (value is not null && index != total)
        {
            value += AppSettings.DEFAULT_SPLITER_STRING;
        }

        return value;
    }
    /// <summary>
    /// 转换字符串为指定对象
    /// </summary>
    /// <typeparam name="TEntitySet">对象类型</typeparam>
    /// <param name="value">字符串值</param>
    /// <param name="index">当前行数</param>
    /// <returns>转换后的对象</returns>
    protected override TEntitySet? ConvertTo<TEntitySet>(string value, long index) where TEntitySet : class
    {
        if (value != "[" && value != "]")
        {
            if (value.EndsWith(AppSettings.DEFAULT_SPLITER_STRING))
            {
                value = value[..^AppSettings.UNIT_TWO];
            }

            return value.ToJsonObject<TEntitySet>();
        }

        return default;
    }
}